package org.example.market.service.UserService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.micrometer.common.util.StringUtils;
import org.example.market.entity.User;
import org.example.market.mapper.UserMapper;
import org.example.market.util.PageResult;
import org.example.market.util.Result;
import org.example.market.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public Result<User> addUser(User user) {
        try {
            // 检查用户编码是否已存在
            User existUser = userMapper.getUserByCode(user.getUserCode());
            if (existUser != null) {
                return Result.error(400, "用户编码已存在");
            }

            // 密码加密处理（自动生成盐值）
            String encryptedPassword = PasswordUtil.encodeDefaultSalt(user.getUserPassword());
            user.setUserPassword(encryptedPassword);
            user.setStatus(1);
            user.setSalt(PasswordUtil.salt());

            userMapper.insertUser(user);
            return Result.success(user);
        } catch (Exception e) {
            return Result.error(500, "添加用户失败: " + e.getMessage());
        }
    }

    public Result<List<User>> getAllUserList() {
        try {
            List<User> users = userMapper.listAllUsers();
            return Result.success(users);
        } catch (Exception e) {
            return Result.error(500, "获取用户列表失败: " + e.getMessage());
        }
    }

    public Result<User> getUserDetail(Long id) {
        try {
            User user = userMapper.getUserById(id);
            if (user != null) {
                return Result.success(user);
            }
            return Result.error(404, "未找到该用户");
        } catch (Exception e) {
            return Result.error(500, "获取用户详情失败: " + e.getMessage());
        }
    }

    public Result<User> updateUser(User user) {
        try {
            // 处理密码更新（如果密码不为空则加密）
            if (StringUtils.isNotBlank(user.getUserPassword())) {
                // 获取原用户信息提取盐值
                User originalUser = userMapper.getUserById(user.getId());
                if (originalUser == null) {
                    return Result.error(404, "用户不存在");
                }

                // 从原密码中提取盐值（18-26位）
                String originalPassword = originalUser.getUserPassword();
                String salt = originalPassword.substring(18, 26);

                // 使用原盐值加密新密码
                String encryptedPassword = PasswordUtil.encode(user.getUserPassword(), salt);
                user.setUserPassword(encryptedPassword);
            }

            userMapper.updateUser(user);
            return Result.success(user);
        } catch (Exception e) {
            return Result.error(500, "更新用户失败: " + e.getMessage());
        }
    }

    public Result<Void> deleteUser(Long id) {
        try {
            userMapper.deleteUserById(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "删除用户失败: " + e.getMessage());
        }
    }

    public Result<Map<String, Object>> login(String userCode, String userPassword) {
        try {
            // 先通过用户编码查询用户
            User user = userMapper.getUserByCode(userCode);
            if (user == null) {
                return Result.error(401, "用户名或密码错误");
            }
            if((int)user.getStatus()==2) {
                return Result.error(401, "该用户被冻结");
            }

            // 使用加密工具验证密码
            boolean isMatch = PasswordUtil.match(userPassword, user.getUserPassword());
            if (isMatch) {
                Map<String, Object> data = new HashMap<>();
                data.put("user", user);
                data.put("token", "mock-token-" + System.currentTimeMillis());
                return Result.success(data);
            }

            return Result.error(401, "用户名或密码错误");
        } catch (Exception e) {
            return Result.error(500, "登录失败: " + e.getMessage());
        }
    }

    public Result<Void> changePassword(Long id, String oldPassword, String newPassword) {
        try {
            User user = userMapper.getUserById(id);
            if (user == null) {
                return Result.error(404, "用户不存在");
            }

            // 验证旧密码
            boolean isMatch = PasswordUtil.match(oldPassword, user.getUserPassword());
            if (!isMatch) {
                return Result.error(400, "旧密码不正确");
            }

            // 提取原盐值加密新密码
            String originalPassword = user.getUserPassword();
            String salt = originalPassword.substring(18, 26);
            String encryptedNewPassword = PasswordUtil.encode(newPassword, salt);

            userMapper.updatePassword(id, encryptedNewPassword);
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "修改密码失败: " + e.getMessage());
        }
    }

    public Result<Void> updateStatus(Long id, Integer status) {
        try {
            User user = userMapper.getUserById(id);
            if (user == null) {
                return Result.error(404, "用户不存在");
            }

            user.setStatus(status);
            userMapper.updateUser(user);
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "更新用户状态失败: " + e.getMessage());
        }
    }

    public Result<Void> updateRole(Long id, Integer status) {
        try {
            User user = userMapper.getUserById(id);
            if (user == null) {
                return Result.error(404, "用户不存在");
            }

            user.setUserRole(status);
            userMapper.updateUser(user);
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "更新用户状态失败: " + e.getMessage());
        }
    }

    public Result<PageResult<User>> findByPage(int currentPage, int pageSize, String userCode, String userName) {
        try {
            // 修复分页逻辑：计算正确的起始索引
            // 第一页（currentPage=1）起始索引为0，对应1~pageSize条数据
            // 第二页（currentPage=2）起始索引为pageSize，对应pageSize+1~2*pageSize条数据
            int startIndex = (currentPage - 1) * pageSize;

            // 传入正确的起始索引和每页条数
            List<User> user = userMapper.findByPage(startIndex, pageSize, userCode, userName);
            int total = userMapper.countByCondition(userCode, userName);

            PageResult<User> pageResult = new PageResult<>();
            pageResult.setList(user);
            pageResult.setTotal(total);
            pageResult.setCurrentPage(currentPage);
            pageResult.setPageSize(pageSize);

            return Result.success(pageResult);
        } catch (Exception e) {
            return Result.error(500, "分页查询用户失败: " + e.getMessage());
        }
    }
}
